<template>
    <div>
        <div>

            <!--
            思路：

            默认渲染 1路 公交线路的 站点表，根据输入框 输入线路数值动态渲染界面

            -->
            <el-card shadow="always" style="text-align: center">
                公交站点管理
            </el-card>

            <div>
                <div class="outside" :style="{'--zhandianwide':zhandianwide+'px'}">
                    <div class="inside">
                        <div class="xinxi">
                            <div class="head1"
                                 style="text-align: center;font-size: 14px;font-weight: bold;border-right: 1px rgb(147, 205, 187) solid;width: 45px;height: 43px;background-color: rgb(155, 231, 208);margin: 0;float: left">
                                开往<br>→
                            </div>
                            <div class="head2"
                                 style="text-align: center;width: auto;line-height: 42px;font-size: 16px;font-weight: bold;margin: 0;background-color: rgb(155, 231, 208);height: 43px;">
                                {{ this.routeInfo.routeName }}
                            </div>
                            <div class="body1" style="background-color: rgb(31, 155, 163); height: 100%">
                                <div
                                        style="margin-left: 3px;line-height: 60px;font-size: 28px;font-weight: bold;color: rgb(247, 251, 249);">
                                    {{ this.routeInfo.id }}路
                                </div>
                                <div
                                        style="margin-left: 3px;line-height: 15px;letter-spacing:2px;font-size: 15px;font-weight: bold;color: rgb(247, 251, 249);">
                                    首班 {{ this.routeInfo.beginTime }} 末班 {{ this.routeInfo.endTime }}
                                </div>
                                <div
                                        style="margin-left: 3px;line-height: 35px;letter-spacing:1px;font-size: 15px;font-weight: bold;color: rgb(247, 251, 249);">
                                    间隔： 不大于{{ this.routeInfo.betweenNum }}分钟一班
                                </div>
                                <div
                                        style="margin-left: 3px;line-height: 15px;letter-spacing:1px;font-size: 15px;font-weight: bold;color: rgb(247, 251, 249);">
                                    票价： {{ this.routeInfo.price }}元
                                </div>
                            </div>
                        </div>
                        <div class="zhandian">
                            <el-table
                                    stripe
                                    class="t"
                                    element-loading-text="拼命加载中"
                                    element-loading-spinner="el-icon-loading"
                                    element-loading-background="rgba(0, 0, 0, 0.8)"
                                    :data="AllData"
                                    border
                                    style="width: 100%;border-top: 4px rgb(54, 166, 173) solid">
                                <el-table-column
                                        align="center"
                                        width="44px"
                                        v-for="(item,index) in allList"
                                        :prop="item.key"
                                        :key="index"
                                        :label="item.siteOrder">
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>


                <el-tooltip class="item" effect="dark" content="切换线路" placement="top-end">
                    <el-autocomplete
                            v-model="routeId"
                            placeholder="请输入内容"
                            @change="this.getAadSet"
                            style="margin-top: 190px"
                    ></el-autocomplete>
                </el-tooltip>


                <el-button type="primary" round style="margin-top: 200px;margin-right:50px;float: right" icon="el-icon-plus"
                           @click="insertSite()">新增
                </el-button>
            </div>

            <!--站点表-->
            <el-table
                    :data="getData"
                    stripe
                    :header-cell-style="tableHeaderColor"
                    element-loading-text="拼命加载中"
                    element-loading-spinner="el-icon-loading"
                    element-loading-background="rgba(0, 0, 0, 0.8)"

                    style="width: 100%;margin-top: 20px">
                <el-table-column
                        prop="siteOrder"
                        label="编号"
                        align="center"
                        width="180">
                </el-table-column>
                <el-table-column
                        prop="siteName"
                        label="站点名称"
                        align="center"
                        width="200">
                </el-table-column>

                <el-table-column
                        label="站点顺序"
                        prop="siteOrder"
                        align="center"
                        width="350">

                    <template slot-scope="scope">
                        <el-input v-model="scope.row.siteOrder" style="width: 300px"></el-input>

                        <!--点击确定提交更新站点顺序-->
                        <el-tooltip class="item" effect="dark" content="提交更新" placement="top-start">
                            <el-button style="margin: 5px" type="text" size="medium" @click="updateSiteOrder(scope.row)">
                                <i class="el-icon-check" aria-hidden="true"></i>
                            </el-button>
                        </el-tooltip>

                    </template>


                </el-table-column>

                <el-table-column
                        align="center"
                        label="操作" :formatter="formatter">
                    <template slot-scope="scope">
                        <el-button type="success" round @click="updateSite(scope.row)">
                            <i class="el-icon-edit" aria-hidden="true"></i>
                            修改
                        </el-button>
                        <el-button type="danger" round @click="deleteOne(scope.row)">
                            <i class="el-icon-delete" aria-hidden="true"></i>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!--新增、修改对话框-->

            <el-dialog :title="title" :visible.sync="dialogInsertSite" width="600px" popper-append-to-body="'false'"
                       style="height: 800px;padding-bottom:20px">

                <div v-if="dialogInsertSite" style="z-index: 99999">

                    <div id="allMap">
                        <div v-if="siteIdInput" style="margin: 5px">编号： {{ inputId }}</div>
                        <!--修改对话框-->
                        <div v-if="titleId==2" id="r-result" style="padding: 10px 5px;">
        <span><span style="color:rgba(0, 0, 0, 0.85);">搜索<span style="margin:0 2px">:</span> </span>
          <span style="margin-left:5px">
            <input type="text" id="suggestId" value="" size="25"
                   style="width:350px;height: 32px;line-height: 15px;padding: 4px 11px;font-size: 12px;border: 1px solid #E8E8E8;border-radius: 4px;"/></span>
        </span>
                            <div style="padding-top:10px"><span>已选择地址：{{ place }} </span>
                                <el-button type="primary" round style="float:right;width: 65px;line-height:10px;margin: 3px"
                                           @click="clearSelect"
                                >清除
                                </el-button>
                            </div>
                            <el-form :model="UpdateInput" :inline="true" label-width="100px">
                                <el-form-item label="确认站点名称">
                                    <el-input v-model="UpdateInput.siteName" autocomplete="off" style="width: 150px"></el-input>
                                </el-form-item>
                                <el-form-item label="确认站点顺序">
                                    <el-input v-model="UpdateInput.siteOrder" autocomplete="off" style="width: 100px"></el-input>
                                </el-form-item>
                            </el-form>
                        </div>
                        <!--新增对话框-->
                        <div v-if="titleId==1" id="r-result1" style="padding: 10px 5px;">
        <span><span style="color:rgba(0, 0, 0, 0.85);">搜索<span style="margin:0 2px">:</span> </span>
          <span style="margin-left:5px">
            <input type="text" id="suggestId" value="" size="25"
                   style="width:350px;height: 32px;line-height: 15px;padding: 4px 11px;font-size: 12px;border: 1px solid #E8E8E8;border-radius: 4px;"/></span>
        </span>
                            <div style="padding-top:10px"><span>已选择地址：{{ place }} </span>
                                <el-button type="primary" round style="float:right;width: 65px;line-height:10px;margin: 3px"
                                           @click="clearSelect"
                                >清除
                                </el-button>
                            </div>

                            <el-form :model="SubmitInput" :inline="true" label-width="100px">
                                <el-form-item label="确认站点名称">
                                    <el-input v-model="SubmitInput.siteName" autocomplete="off" style="width: 150px"></el-input>
                                </el-form-item>
                                <el-form-item label="确认站点顺序">
                                    <el-input v-model="SubmitInput.siteOrder" autocomplete="off" style="width: 100px"></el-input>
                                </el-form-item>
                            </el-form>
                        </div>


                        <div id="searchResultPanel"
                             style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
                        <div id="bookingMap"></div>
                    </div>


                    <div slot="footer" class="dialog-footer">
                        <el-button @click="">取 消</el-button>
                        <el-button type="primary" @click="insertOrUpdate()">提 交</el-button>
                    </div>
                </div>

            </el-dialog>


        </div>
    </div>
</template>

<script>
    let map;
    export default {
        name: "sitesInformation",
        data() {
            return {
                title: '',
                titleId: 1,
                routeId: 524,
                dialogInsertSite: false,
                siteIdInput: false,
                inputId: 0,
                top: 0,
                place: '',
                routeInfo: {
                    id: 0,
                    routeName: '',
                    beginTime: '',
                    endTime: '',
                    betweenNum: 0,
                    price: 0,
                },
                zhandianwide: 0,
                AllData: [],
                allList: [],
                getData: [],
                SubmitInput: {
                    siteName: '',
                    routeId: '',
                    siteOrder: '',
                },
                UpdateInput: {
                    siteName: '',
                    siteId: '',
                    siteOrder: '',
                }

            }

        },

        mounted() {
            //初始化地图前先将scrollTop设置为0，否则会出现放大/缩小位置偏移
            // this.mapOpen()
            // this.initMap()
        },

        beforeDestroy() {
            map = null
            //关闭地图前将scrollTop设置为原始值
            this.mapClose()
        },
        created() {
            this.getAadSet()
        },
        methods: {
            hello() {
                console.log(1);
                console.log("1231234")
                this.place = ''
                this.initMap()
            },
            getAadSet() {
                console.log(this.routeId)
                this.AllData = []
                this.allList = []
                this.getData = []
                this.getRouteInfo();
                this.setData();

            },
            getRouteInfo() {
                this.$http({
                    url: '/route/getOneById',
                    method: 'GET',
                    params: {
                        id: this.routeId
                    }
                }).then(result => {
                    console.log(result)
                    if (result.status == 200) {
                        this.routeInfo.id = result.data.id;

                        this.routeInfo.routeName = result.data.routeName;
                        this.routeInfo.beginTime = result.data.beginTime;
                        this.routeInfo.endTime = result.data.endTime;
                        this.routeInfo.betweenNum = result.data.betweenNum;
                        this.routeInfo.price = result.data.price;
                        this.timer = setTimeout(() => {   //设置延迟执行
                            this.loading = false
                        }, 200);
                    }
                })
            },
            setData() {
                this.$http({
                    url: '/sites/getSiteById',
                    method: 'GET',
                    params: {
                        id: this.routeId
                    }
                }).then(result => {
                    console.log(result);
                    if (result.status == 200) {

                        /*表格动态宽度*/
                        if (result.data.length <= 12) {
                            this.zhandianwide = 210 + 44 * result.data.length + 13
                        } else {
                            this.zhandianwide = 210 + 44 * 12 + 13
                        }


                        for (let i = 0; i < result.data.length; i++) {
                            this.getData.push(result.data[i]);
                        }
                        console.log(this.getData);
                        var a = {};
                        var b = [];
                        // a['title'] = this.getData[i].title;
                        var x = 0;
                        var join = 0;
                        for (var i in this.getData) {
                            x += 1;
                            b.push({siteOrder: "" + this.getData[i].siteOrder, key: 'siteName' + x});
                            a['siteName' + x] = this.getData[i].siteName;

                        }
                        this.AllData.push(a);
                        this.allList = b;
                        console.log(this.allList);
                    } else {
                        this.$message({
                            showClose: true,
                            message: '发生了未知错误',
                            type: 'error'
                        })
                    }
                })
            },
            /*增加该路线的站点*/
            insertSite(data) {
                this.SubmitInput.siteOrder = ''
                this.SubmitInput.siteName = ''
                this.title = '增加站点'
                this.titleId = 1
                this.dialogInsertSite = true

                setTimeout(() => {
                    this.mapOpen()
                    this.initMap()
                }, 0);

            },
            updateSite(data) {
                this.UpdateInput.siteId = 0
                this.UpdateInput.siteOrder = 0
                this.UpdateInput.siteName = 0
                this.titleId = 2
                this.title = '修改站点'
                this.dialogInsertSite = true
                this.UpdateInput.siteOrder = data.siteOrder
                this.UpdateInput.siteName = data.siteName
                this.UpdateInput.siteId = data.siteId
                console.log(this.UpdateInput.siteName)
                console.log(this.UpdateInput.siteId)
                setTimeout(() => {
                    this.mapOpen()
                    this.initMap()
                }, 0);

            },
            /*更新站点顺序*/
            updateSiteOrder(data) {
                console.log(data)

                this.$http({
                    url: '/sites/updateSiteOrderBySId',
                    method: 'get',
                    params: {
                        siteOrder: data.siteOrder,
                        siteId: parseInt(data.siteId)
                    }

                }).then(result => {
                    if (result.status == 200) {
                        this.$message({
                            showClose: true,
                            message: '更新信息成功',
                            type: 'success'
                        });
                        this.getAadSet();
                    } else {
                        this.$message({
                            showClose: false,
                            message: '更新失败',
                            type: 'error'
                        });
                        this.getAadSet();
                    }
                })
            },
            /*对话框提交修改或新增*/
            insertOrUpdate() {
                this.dialogInsertSite = false
                console.log(this.titleId)
                /*新增站点*/
                if (this.titleId == 1) {
                    this.$http({
                        url: 'sites/insertOne',
                        method: 'POST',
                        params: {
                            siteName: this.SubmitInput.siteName,
                            routeId: this.routeId,
                            siteOrder: this.SubmitInput.siteOrder
                        }

                    }).then(result => {
                        if (result.data > 0) {
                            this.$notify({
                                title: '成功',
                                message: '添加成功',
                                type: 'success'
                            })
                            this.getAadSet()

                        } else {
                            this.$notify({
                                title: '失败',
                                message: '添加失败',
                                type: 'error'
                            })
                            this.getAadSet()
                        }
                    })
                }
                /*修改站点*/
                if (this.titleId == 2) {
                    this.$http({
                        url: '/sites/updateOne',
                        method: 'put',
                        data: {
                            siteName: this.UpdateInput.siteName,
                            siteOrder: parseInt(this.UpdateInput.siteOrder),
                            siteId: parseInt(this.UpdateInput.siteId),
                        }

                    }).then(result => {
                        console.log(result);
                        if (result.data > 0) {
                            this.$notify({
                                title: '成功',
                                message: '修改成功',
                                type: 'success'
                            })
                            this.getAadSet()

                        } else {
                            this.$notify({
                                title: '失败',
                                message: '未知错误',
                                type: 'error'
                            })
                            this.getAadSet()
                        }
                    })
                }
            },
            deleteOne(data) {

                this.$http({
                    url: '/sites/deleteOne',
                    method: 'delete',
                    params: {
                        siteId: parseInt(data.siteId)
                    }

                }).then(result => {
                    if (result.status == 200) {
                        this.$message({
                            showClose: true,
                            message: '删除站点成功',
                            type: 'success'
                        });
                        this.getAadSet();
                    } else {
                        this.$message({
                            showClose: false,
                            message: '删除站点失败',
                            type: 'error'
                        });
                        this.getAadSet();
                    }
                })
            },
            tableHeaderColor({rowIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #C0C4CC;color: #fff;font-weight: 500;height:51px'
                }
            },
            initMap() {
                //实例化地图
                map = new BMap.Map("bookingMap");
                //设置地图中心点坐标，比例大小
                var point = new BMap.Point(116.331398, 39.897445);
                map.centerAndZoom(point, 12);

                //启用滚轮放大缩小，默认禁用
                map.enableScrollWheelZoom();
                //启用地图拖拽事件，默认启用
                map.enableInertialDragging();
                //启用地图缩放，默认禁用
                map.enableContinuousZoom();
                //默认手型改为十字星
                map.setDefaultCursor("crosshair");


                //定位
                this.getPlace()
                //添加地图控制器
                this.addControl()
                //添加监听
                this.addListener()
            },
            addControl() {
                // 地图缩放控件
                const topLeftControl = new BMap.ScaleControl({anchor: BMAP_ANCHOR_BOTTOM_LEFT})
                // 城市选择控件
                const size = new BMap.Size(10, 20);
                const cityListControl = new BMap.CityListControl({anchor: BMAP_ANCHOR_TOP_RIGHT, offset: size})
                // 比例尺控件
                const topLeftNavigation = new BMap.NavigationControl()
                map.addControl(topLeftControl)
                map.addControl(topLeftNavigation)
                map.addControl(cityListControl)
            },
            addListener() {
                let _this = this

                // 百度地图API功能
                function G(id) {
                    return document.getElementById(id);
                }

                var geoc = new BMap.Geocoder();
                //点击监听，获得点击地址
                map.addEventListener("click", function (e) {
                    _this.addMarker(e.point);
                    geoc.getLocation(e.point, function (rs) {
                        var addComp = rs.addressComponents;
                        var address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                        _this.place = address
                        _this.$emit('submit', {...e.point, place: _this.place})     //直接地图选择
                    });

                });
                //输入监听
                var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
                    {
                        "input": "suggestId"
                        , "location": map
                    });
                ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
                    var str = "";
                    var _value = e.fromitem.value;
                    var value = "";
                    if (e.fromitem.index > -1) {
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                    value = "";
                    if (e.toitem.index > -1) {
                        _value = e.toitem.value;
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
                    G("searchResultPanel").innerHTML = str;
                });

                var myValue;
                ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
                    _this.initMap()
                    var _value = e.item.value;
                    myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                    // G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
                    _this.place = myValue
                    setPlace();
                });

                function setPlace() {
                    map.clearOverlays();    //清除地图上所有覆盖物
                    function myFun() {
                        var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                        _this.$emit('submit', {...pp, place: _this.place})    //搜索--选择
                        map.centerAndZoom(pp, 18);
                        map.addOverlay(new BMap.Marker(pp));    //添加标注
                    }

                    var local = new BMap.LocalSearch(map, { //智能搜索
                        onSearchComplete: myFun
                    });
                    local.search(myValue);
                }
            },
            addMarker(point) {
                console.log(point, 'wj')
                var marker = new BMap.Marker(point);
                map.clearOverlays();
                map.addOverlay(marker);
            },
            //初时定位
            getPlace() {
                let _this = this

                function myFun(result) {
                    var cityName = result.name;
                    map.setCenter(cityName);
                    if (!cityName) {
                        _this.place = cityName
                    }
                }

                var myCity = new BMap.LocalCity();
                myCity.get(myFun);

            },
            mapOpen() {
                this.top = this.getScrollTop()
                if (this.top) {
                    this.setScrollTop(0)
                }
            },
            mapClose() {
                this.setScrollTop(this.top);
                this.top = 0;
            },
            getScrollTop() {
                let scrollTop = 0;
                if (document.documentElement && document.documentElement.scrollTop) {
                    scrollTop = document.documentElement.scrollTop;
                } else if (document.body) {
                    scrollTop = document.body.scrollTop;
                }
                return scrollTop;
            },
            setScrollTop(top) {
                if (!isNaN(top)) {
                    if (document.documentElement && document.documentElement.scrollTop !== undefined) {
                        document.documentElement.scrollTop = top;
                    } else if (document.body) {
                        document.body.scrollTop = top;
                    }
                }
            },
            clearSelect() {
                console.log("1231234")
                this.place = ''
                this.initMap()
            },
            // 用经纬度设置地图中心点(反显时调用)
            theLocation(point) {
                let _this = this
                let map = new BMap.Map("bookingMap");
                map.clearOverlays();
                let new_point = new BMap.Point(point.lng, point.lat);
                // let new_point = new BMap.Point(116.281037,40.054213);
                map.centerAndZoom(new_point, 19)           //重新定位

                let geoc = new BMap.Geocoder();
                //根据经纬度获得详细地址
                geoc.getLocation(new_point, function (rs) {
                    var addComp = rs.addressComponents;
                    var address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                    _this.place = address
                });
                let marker = new BMap.Marker(new_point);  // 创建标注
                map.addOverlay(marker);              // 将标注添加到地图中
                map.panTo(new_point);
            }
        }


    }
</script>

<style scoped>

    h3 {
        text-align: center;
        margin: 10px;
        color: rgb(27, 155, 163);
        font-size: 24px;
        font-family: "Avenir", Helvetica, Arial, sans-serif;
        letter-spacing: 2.5px;
    }

    .outside {
        float: left;
        margin-bottom: 80px;
        width: var(--zhandianwide);
        position: center;
    }

    .inside {
        height: 157px;
    }

    .t {
        border: rgb(195, 227, 232) 1px solid;
        width: 20px;

    }

    .xinxi {
        float: left;
        width: 210px;
        height: 100%;

    }

    .zhandian {


        display: flex;
        margin: 10px;
    }

    .shousuo {
        margin: 10px;
    }

    .map {
        width: 400px;
        height: 300px;
    }

    #allMap {
        width: auto;
        height: 350px;
        padding-bottom: 100px;
    }

    #bookingMap {
        width: 100%;
        height: 88%;

    }

    #r-result {
        width: 100%;
        z-index: 100;
    }

    input:focus {
        border-color: #40a9ff !important;
        border-right-width: 1px !important;
        outline: 0 !important;
        -webkit-box-shadow: 0 0 0 2px rgb(24 144 255 / 20%) !important;
        box-shadow: 0 0 0 2px rgb(24 144 255 / 20%) !important;
    }

</style>
<style>
    .tangram-suggestion-main {
        z-index: 99999;
    }

</style>
